package cn.itsource.estest;

import org.elasticsearch.action.index.IndexRequestBuilder;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchRequestBuilder;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.sort.SortOrder;
import org.elasticsearch.transport.client.PreBuiltTransportClient;
import org.junit.Test;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.HashMap;
import java.util.Map;

public class Es {
    /**
     * 获取连接的工具类
     * @return
     */
    public TransportClient getClient(){
        Settings settings = Settings.builder()
                .put("client.transport.sniff", true).build();
        TransportClient client = null;
        try {
            client = new PreBuiltTransportClient(settings)
                    .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("127.0.0.1"), 9300));
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
        return client;
    }
    @Test
    public void add(){ // 添加方法
        for (int i= 2; i<20; i++){
            Map<String, Object> map = new HashMap<>();
            map.put("id", i);
            map.put("name", "ysf"+(i%2==0?1:0));
            map.put("username", "qr"+(i%2==0?1:0));
            map.put("age", 12+i);
            // 创建连接
            TransportClient client = getClient();
            // 创建索引
            IndexRequestBuilder builder = client.prepareIndex("pethome", "user", ""+i);
            builder.setSource(map);
            // 执行操作
            IndexResponse response = builder.get();
            client.close();
        }
    }

    @Test
    public void load(){ // 查询单个数据
        TransportClient client = getClient();
        System.out.println(client.prepareGet("pethome","user","3").get().getSource());
        client.close();
    }

    @Test
    public void update (){ // 修改
        TransportClient client = getClient();
        Map<String, Object> map = new HashMap<>();
        map.put("age", 1);

        // 必须要.get()
        client.prepareUpdate("pethome","user","1").setDoc(map).get();

        client.close();
    }

    @Test
    public void delete(){ // 删除
        TransportClient client = getClient();
        client.prepareDelete("pethome","user","1").get();
        client.close();
    }

    @Test
    public void search(){ // 综合查询
        // 创建连接
        TransportClient client = getClient();
        // 创建索引
        SearchRequestBuilder search = client.prepareSearch("pethome");
        // 对年龄进行降序排列
        search.addSort("age", SortOrder.DESC);
        // 一页展示10条数据，从第一页开始展示
        search.setFrom(0);
        search.setSize(7);
        // 创建bool组合查询
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        // 组合查询的第一级为must必须匹配的，里面使用match匹配
        boolQueryBuilder.must(QueryBuilders.matchQuery("name", " ysf1 ysf0"));
        // 组合查询和must平级的还有filter过滤操作.里面平级的有term匹配方法，和range进行筛选年龄最小为10最大为30
        boolQueryBuilder.filter(QueryBuilders.termQuery("username", "qr1"))
                .filter(QueryBuilders.rangeQuery("age").gte(10).lte(30));
        // 索引执行查询的操作，必须有.get()方法
        SearchResponse searchResponse = search.setQuery(boolQueryBuilder).get();
        // 获取查询出来的信息对象
        SearchHits hits = searchResponse.getHits();
        // 获取查询出来的总数
        long totalHits = hits.getTotalHits();
        System.out.println("一共：" + totalHits+"条");
        // 获取查询出来的所有信息，进行遍历
        SearchHit[] hits1 = hits.getHits();
        for (SearchHit searchHit : hits1){
            Map<String, Object> source = searchHit.getSource();
            System.out.println(source);
        }
    client.close();
    }
}
